package top.gugulh.jx.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.gugulh.jx.common.R;
import top.gugulh.jx.pojo.Users;
import top.gugulh.jx.pojo.vo.UsersVo;
import top.gugulh.jx.service.UsersService;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UsersService usersService;

    @PostMapping("/register-or-login")
    public R registerOrLogin(@RequestBody Users user) {
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())) {
            return R.error("用户名或密码不能为空");
        }
        boolean exist = usersService.searchUsernameExist(user.getUsername());
        Users userResult = null;
        if (exist) {
            userResult = usersService.searchUserByUsernameAndPwd(user.getUsername(), DigestUtil.md5Hex(user.getPassword()));
            if (userResult == null) {
                return R.error("用户名或密码不正确");
            }
        } else {
            user.setNickname(user.getUsername());
            user.setFaceImage("");
            user.setFaceImageBig("");
            user.setPassword(DigestUtil.md5Hex(user.getPassword()));

            userResult = usersService.createUser(user);
        }
        UsersVo userVo = new UsersVo();
        BeanUtil.copyProperties(userResult, userVo);
        return R.ok().put("result", userVo);
    }
}
